﻿/*************************************
 * Creator:SW-PeiYang
 * DateTime:2023/12/8 11:09:56
 * Description:<Description>
 * CopyRight:中广核研究院有限公司
 * ***********************************/

using Cpjit.SunnyPaine.Toolkit.Net.Sockets.IDataHandlingApdapter;
using System;
using System.Net.Sockets;

namespace Cpjit.SunnyPaine.Toolkit.Net.Sockets.Util
{
    /// <summary>
    /// 数据处理适配器扩展。
    /// </summary>
    public static class DataHandlingAdapterExtension
    {
        /// <summary>
        /// 发送消息。
        /// </summary>
        /// <param name="adapter">数据处理适配器。</param>
        /// <param name="socket">Socket通讯对象。</param>
        /// <param name="datas">数据。</param>
        /// <param name="isAsync">是否异步发送。</param>
        /// <param name="action">（如果异步发送）异步发送的回读方法。</param>
        public static void Send(this IDataHandlingAdapter adapter, Socket socket, byte[] datas, bool isAsync, Action<IAsyncResult> action = null)
        {
            if (adapter == null)
            {
                if (isAsync)
                {
                    socket.BeginSend(datas, 0, datas.Length, SocketFlags.None,
                        new AsyncCallback(action), socket);
                }
                else
                {
                    socket.Send(datas);
                }
            }
            else
            {
                adapter.PreviewSend(socket, datas, isAsync);
            }
        }
    }
}
